package com.xgf.demo.filter;

import com.xgf.demo.util.UserUtil;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*", filterName = "loginFilter")
public class UserFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        fillUserInfo((HttpServletRequest) request);
        chain.doFilter(request, response);
        clearAllUserInfo();
    }

    private void fillUserInfo(HttpServletRequest request) {
        String user = getUserFromSession(request);
        if (user != null) {
            UserUtil.getInstance().setUser(user);
        }

    }

    private void clearAllUserInfo() {
        UserUtil.getInstance().clearAllUserInfo();
    }

    private String getUserFromSession(HttpServletRequest request) {
        // TODO 如果不参加session，model.addAttribute(UserUtil.KEY_USER, username);报错
        HttpSession session = request.getSession(true);

        if (session == null) {
            return null;
        }

        // 从session中获取用户信息放到工具类中
        return (String) session.getAttribute(UserUtil.KEY_USER);

    }
     @Override
    public void destroy() {

    }
}
